#include "StdAfx.h"
#include ".\xmlnodes.h"

CXmlNodes::CXmlNodes(MSXML2::IXMLDOMNodeListPtr pNodeList)
{
    m_pNodeList = pNodeList;
}

CXmlNodes::CXmlNodes( CXmlNodes & refNodes )
{
    m_pNodeList = refNodes.m_pNodeList;
}

CXmlNodes::CXmlNodes(void)
: m_pNodeList(NULL)
{
}

CXmlNodes::~CXmlNodes(void)
{
    Release();
}

//////////////////////////////////////////////////////////////////////////
void CXmlNodes::Release(void)
{
    RELEASE_PTR(m_pNodeList);
}

CXmlNodesPtr CXmlNodes::operator = ( CXmlNodesPtr pNodes IN )
{
    RELEASE_PTR(m_pNodeList);
    
    m_pNodeList = pNodes->m_pNodeList;
    return pNodes;
}

CXmlNodes & CXmlNodes::operator = (CXmlNodes & refNodes)
{
    RELEASE_PTR(m_pNodeList);
    
    m_pNodeList = refNodes.m_pNodeList;
    return (*this);
}

LONG CXmlNodes::GetCount(void)
{
    ASSERT( m_pNodeList != NULL );
    
    try
    {
        return m_pNodeList->length;
    }
    catch ( _com_error e )
    {
        TRACE( _T("CXmlNodes::GetCount exception: %s\n"), e.ErrorMessage());
        ASSERT( FALSE );
        return -1;
    }
}

CXmlNodePtr CXmlNodes::GetItem( LONG nIndex )
{
    ASSERT( m_pNodeList != NULL );
    ASSERT( nIndex >= 0 && nIndex < GetCount() );
    
    CXmlNodePtr pNode ( new CXmlNode(m_pNodeList->item[nIndex]) );
    
    return pNode;
}

CXmlNodePtr CXmlNodes::operator[] ( LONG lIndex )
{
    return GetItem(lIndex);
}

CXmlNodePtr CXmlNodes::GetItem( LPCTSTR lpszName )
{
    ASSERT( m_pNodeList != NULL );
    ASSERT( lpszName != NULL );
    
    CXmlNodePtr pNode ( new CXmlNode() );
    
    try
    {
        HRESULT hr = S_OK;
        CString strName;
        BSTR bstr = NULL;
        MSXML2::IXMLDOMNodePtr pItem = NULL; 
        
        for( int i = 0; i < m_pNodeList->length; i++)
        {
            pItem = m_pNodeList->item[i];
            
            hr = pItem->get_nodeName(&bstr);  
            
            strName = (LPCTSTR)_bstr_t( bstr, true);
            if( bstr != NULL )
            {
                SysFreeString(bstr);
                bstr = NULL;
            }
            
            if( strName.Compare(lpszName) == 0 )
            {
                pNode->m_pNode = pItem;
                RELEASE_PTR(pItem);
                return pNode;
            }
            
            RELEASE_PTR(pItem);
        }
    }
    catch ( _com_error e )
    {
        TRACE( _T("CXmlNodes::GetItem exception: %s\n"), e.ErrorMessage());
        ASSERT( FALSE );
    }
    
    return pNode;
}

CXmlNodePtr CXmlNodes::operator[] ( LPCTSTR lpszName )
{
    return GetItem(lpszName);
}